<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import releaseModal from './components/modalCont/releaseModal.vue';
import authorizeModal from './components/modalCont/authorizeModal.vue';
import moreOperateImg from '@/assets/images/more_operate.svg';
import { onClickOutside } from '@vueuse/core';
import API from '@/services';
import router from '@/router';
import * as RouteNames from '@/router/consts';
import { store } from '@/store';
import collectIcon from '@/assets/images/collect_icon.svg';
import collectLineIcon from '@/assets/images/collect_line_icon.svg';
import collectLineIconHover from '@/assets/images/collect_line_icon_hover.svg';

const {
  board: { deleteById, putCollectById, deleteCollectById, deletePublishById },
  metricsBoard: { postMetricsBoardDuplicate },
  metricsTree: { postDuplicate }
} = API;
const popoverVisible = ref(false);
const cardOperate = computed(() => {
  return [
    {
      id: 0,
      name: '发布'
    },
    {
      id: 1,
      name: '下线'
    },
    {
      id: 6,
      name: '编辑发布'
    },
    {
      id: 2,
      name: '复制'
    },
    {
      id: 3,
      name: '授权'
    },
    // {
    //   id: 4,
    //   name: '分享'
    // },
    {
      id: 5,
      name: '删除'
    }
  ];
});

const props = withDefaults(
  defineProps<{
    list: defs.BoardVO[];
    isOperate?: boolean;
    fromWho?: string;
    showCreateBy?: boolean;
    dashborderType?: string;
  }>(),
  {
    list: () => [],
    isOperate: true,
    fromWho: '',
    showCreateBy: true,
    dashborderType: ''
  }
);

const releaseChildRef = ref();
const authorizeChildRef = ref();
const dashboardReleaseTitle = ref('');
const dashboardAuthorizeTitle = ref('');
const releaseTitle = computed(() => {
  return props.fromWho === 'mine' ? dashboardReleaseTitle.value : '发布指标树';
});
const authorizeTitle = computed(() => {
  return props.fromWho === 'mine'
    ? dashboardAuthorizeTitle.value
    : '指标树授权';
});
const emit = defineEmits(['updateList']);
const cardId = ref(0);
const descTooltip = ref(false);

// 显示操作项
const showPopover = (id: any) => {
  cardId.value = id;
  console.log('显示操作项');
  popoverVisible.value = !popoverVisible.value;
};
const popoverImg = ref();
const toNext = (operateItem: any, item: defs.BoardVO) => {
  switch (operateItem.id) {
    case 0:
      release(item);
      break;
    case 1:
      offline(item.id);
      break;
    case 2:
      copyCard(item);
      break;
    case 3:
      authorize(item);
      break;
    case 5:
      deleteCard(item);
      break;
    case 6:
      editRelease(item);
    default:
      '';
  }
  popoverVisible.value = false;
};
onClickOutside(popoverImg, (event) => {
  popoverVisible.value = false;
});

// 发布
const release = (item: defs.BoardVO) => {
  dashboardReleaseTitle.value = '发布' + item.name;
  releaseChildRef.value.showReleaseModal(item);
};

// 下线
const offLineFetch = async (id: number) => {
  try {
    let res = await deletePublishById({ id });
    return res;
  } catch (error) {
    throw error;
  }
};
const offline = (id: any) => {
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '是否确定下线该指标树？',
    content: '下线后不可恢复',
    simple: false,
    closable: true,
    okText: '确定下线',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      offLineFetch(id)
        .then((res: any) => {
          if (res.code === 200) {
            Message.success('下线成功');
            emit('updateList');
          } else {
            Message.error('下线失败');
          }
        })
        .finally(() => {
          done(true);
        });
    }
  });
};

// 复制指标树
const copyTree = async (id: number) => {
  try {
    const res = await postDuplicate({ boardId: id });
    return res;
  } catch (error) {
    throw error;
  }
};

// 复制看板
const copyDashboard = async (id: number) => {
  try {
    const res = await postMetricsBoardDuplicate({ boardId: id });
    return res;
  } catch (error) {
    throw error;
  }
};

// 复制
const copyCard = (item: any) => {
  if (props.fromWho === 'mine') {
    console.log('复制看板');
    copyDashboard(item.id).then((res: any) => {
      if (res.code === 200) {
        Message.success('复制成功');
        emit('updateList');
      } else {
        Message.error(res.msg);
      }
    });
  }

  if (props.fromWho === 'tree') {
    console.log('复制指标树');
    copyTree(item.id).then((res: any) => {
      if (res.code === 200) {
        Message.success('复制成功');
        emit('updateList');
      } else {
        Message.error(res.msg);
      }
    });
  }
};

// 授权
const authorize = (item: any) => {
  dashboardAuthorizeTitle.value = item.name + '授权';
  authorizeChildRef.value.showAuthorizeModal(item);
};

// 删除
const deleteFetch = async (id: any) => {
  try {
    let res = await deleteById({ id });
    return res;
  } catch (error) {
    throw error;
  }
};
const deleteCard = (item: defs.BoardVO) => {
  if (item.isPublished) {
    Message.error('该看板已发布，请先下线再删除');
    return;
  }
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '是否确定删除该卡片？',
    content: '删除后不可恢复',
    simple: false,
    closable: true,
    okText: '确定删除',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      deleteFetch(item.id)
        .then((res: any) => {
          if (res.code === 200) {
            Message.success('删除成功');
            emit('updateList');
          } else {
            Message.error(res.msg);
          }
        })
        .finally(() => {
          done(true);
        });
    }
  });
};

// 编辑发布
const editRelease = (item: defs.BoardVO) => {
  dashboardReleaseTitle.value = '编辑发布' + item.name;
  releaseChildRef.value.showReleaseModal(item, 'isEdit');
};

// 跳转指标树详情
const metricsTreeDetail = (item: defs.BoardVO) => {
  if (item.type === 2) {
    store.commit('indextree/getMetricsTreeName', item.name);
    store.commit('indextree/getMetricsDescript', item.description);
    store.commit('indextree/getMetricsPublish', item.isPublished);
    descTooltip.value = false;
    let query: any = {
      id: item.id
    };
    if (props?.dashborderType === 'public') {
      query.source = 'public';
    } else {
      delete query.source;
    }
    router.push({
      name: RouteNames.ROUTER_METRICS_TREE_DETAIL,
      query: {
        ...query
      }
    });
  } else if (item.type === 1) {
    router.push({
      name: RouteNames.ROUTER_METRICS_DASHBOARD_DETAIL,
      params: { id: item.id, type: item.reviewType === 1 ? '' : '1' }
    });
  } else {
    Message.error('页面建设中...');
  }
};

// 收藏
const getCollect = async (item: any) => {
  const id = item.id;
  putCollectById({ id })
    .then((res) => {
      if (res.code === 200) {
        Message.success('收藏成功');
        item.favorite = !item.favorite;
      } else {
        Message.error(res.msg);
      }
    })
    .catch((error) => {
      Message.error('收藏失败');
    });
};

// 取消收藏
const cancelCollect = async (item: any) => {
  const id = item.id;
  deleteCollectById({ id })
    .then((res) => {
      if (res.code === 200) {
        Message.success('取消收藏成功');
        item.favorite = !item.favorite;
      } else {
        Message.error(res.msg);
      }
    })
    .catch((error) => {
      Message.error('取消失败');
    });
};

// 更新当前看板
const updateItem = () => {
  emit('updateList');
};

// 鼠标移入
const onMouseenter = (id: any) => {
  cardId.value = id;
};
// 鼠标移出
const onMouseleave = () => {
  cardId.value = 0;
};
</script>

<template>
  <div
    class="card-item"
    v-for="item in props.list"
    :key="item.id"
    @click="metricsTreeDetail(item)"
  >
    <a-popover
      :content-style="{ width: '148px', padding: '0' }"
      trigger="click"
      content-class="popper-operate"
      style="padding: 0"
      :popup-visible="popoverVisible && cardId === item.id"
      position="tr"
      :arrow-style="{ display: 'none' }"
    >
      <div>
        <img
          class="card-item-is-collect-icon"
          style="width: 16px; height: 16px"
          @click.stop="cancelCollect(item)"
          v-if="!props.isOperate && item.favorite"
          :src="collectIcon"
        />
        <img
          class="card-item-is-collect-icon"
          style="width: 16px; height: 16px"
          @click.stop="getCollect(item)"
          v-if="!props.isOperate && !item.favorite"
          @mouseleave="onMouseleave()"
          @mouseenter="onMouseenter(item.id)"
          :src="item.id === cardId ? collectLineIconHover : collectLineIcon"
        />
        <span class="card-item-operate-wrap">
          <img
            ref="popoverImg"
            class="card-item-operate-img"
            :src="moreOperateImg"
            v-show="props.isOperate"
            @click.stop="showPopover(item.id)"
          />
        </span>
        <p class="card-item-name">{{ item.name }}</p>
        <!-- :popup-visible="descTooltip" -->
        <a-tooltip
          :content="item.description"
          position="bottom"
          v-if="item.description"
        >
          <!-- @mouseleave="
              () => {
                descTooltip = false;
              }
            "
            @mouseenter="
              () => {
                descTooltip = true;
              }
            " -->
          <p class="card-item-desc">
            {{ item.description }}
          </p>
        </a-tooltip>
        <p class="card-item-desc" v-else>{{ item.description }}</p>
        <span
          style="
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: rgb(155, 159, 171);
          "
        >
          <span>ID: {{ item.id }}</span>
          <span
            class="card-item-status"
            style="
              height: 20px;
              line-height: 20px;
              display: inline-block;
              text-align: center;
            "
            :style="
              item.isPublished
                ? { backgroundColor: '#e6f1fe' }
                : { backgroundColor: 'transparent', color: 'transparent' }
            "
            >{{ item.isPublished ? '已发布' : '未发布' }}</span
          >
        </span>

        <div class="card-item-msg">
          <span class="card-item-msg-num">指标数：{{ item.metricsNum }}</span>
          <span
            class="card-item-msg-creater"
            v-show="props.showCreateBy && item.createBy"
            >创建人：{{ item.createBy }}</span
          >
        </div>
      </div>
      <template #content>
        <ul class="operate-ul">
          <li
            class="operate-item"
            v-for="operateItem in cardOperate"
            :key="operateItem.id"
            @click="toNext(operateItem, item)"
            v-show="
              (operateItem.name !== '发布' && item.isPublished) ||
              (operateItem.name !== '下线' &&
                operateItem.name !== '编辑发布' &&
                !item.isPublished)
            "
          >
            <a-button type="text" class="operate-btn">{{
              operateItem.name
            }}</a-button>
          </li>
        </ul>
      </template>
    </a-popover>
  </div>
  <release-modal
    ref="releaseChildRef"
    :title="releaseTitle"
    @update-item="updateItem"
  ></release-modal>
  <authorize-modal
    ref="authorizeChildRef"
    :title="authorizeTitle"
    @update-item="updateItem"
  ></authorize-modal>
</template>

<style lang="scss" scoped>
@import '~@/assets/styles/mixin.scss';
.card-item {
  background: url('@/assets/images/card_bg.svg') no-repeat;
  border-bottom: 1px solid #eef1f9;
  background-size: cover;
  border-radius: 3px;
  position: relative;
  padding: 18px;
  box-sizing: border-box;
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  margin: 9px;
  width: calc(25% - 18px);
  cursor: pointer;
  height: 174px;
  &:hover {
    box-shadow: 0px 3px 12px 0px rgba(52, 62, 88, 0.08);
    .card-item-operate-img {
      display: block;
      right: 16px;
      top: 16px;
    }
  }
  &-is-collect-icon,
  &-no-collect-icon {
    position: absolute;
    right: 16px;
    top: 20px;
  }
  &-operate-wrap {
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
  &-operate-img {
    width: 20px;
    height: 20px;
    display: none;
    position: absolute;
  }
  &-name {
    font-size: 16px;
    color: #33353b;
    line-height: 24px;
    font-weight: 600;
    margin: 0 0 6px 0;
    width: 90%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
    height: 22px;
  }
  &-desc {
    font-size: 14px;
    color: #60646f;
    line-height: 22px;
    margin: 0 0 18px 0;
    width: 100%;
    height: 42px;
    box-sizing: border-box;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    cursor: pointer;
  }
  &-status {
    border-radius: 2px;
    color: #3c6eff;
    font-weight: 500;
    text-align: center;
    margin-bottom: 6px;
    box-sizing: border-box;
    font-size: 12px;
    padding: 0 6px;
  }
  &-msg {
    font-size: 14px;
    color: #9b9fab;
    line-height: 22px;
    margin-top: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>

<style lang="scss">
.popper-operate {
  margin: 0;
  position: absolute;
  right: -10px;
  top: 32px;
  .arco-popover-content {
    margin-top: 0;
    .operate-ul {
      width: 100%;
      padding: 0;
      margin: 0;
      list-style-type: none;
      li {
        width: 100%;
        font-size: 14px;
        color: #33353b;
        line-height: 22px;
        font-weight: 400;
        box-sizing: border-box;
        padding: 7px 0 7px 12px;
        cursor: pointer;
        &:hover {
          background: #f6f8fc;
        }
        .operate-btn {
          color: #33353b;
        }
      }
    }
  }
}
// .arco-popover-popup-arrow {
//   display: none;
// }
</style>
